//
//  WatermarkCameraViewController.m
//  GolfFriend
//
//  Created by Vescky on 14-5-13.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "WatermarkCameraViewController.h"
#import <ImageIO/ImageIO.h>
#import "GPUImage.h"
#import "DateUtility.h"
#import "SVProgressHUD.h"

@interface WatermarkCameraViewController ()<UITextViewDelegate> {
    AVCaptureSession *_session;
    AVCaptureDeviceInput *_captureInput;
    AVCaptureStillImageOutput *_captureOutput;
    AVCaptureVideoPreviewLayer *_preview;
    AVCaptureDevice *_device;
    
    UIImage *_finishImage;
}
@end

@implementation WatermarkCameraViewController

@synthesize cameraView = _cameraView;
@synthesize takePhotoButton = _takePhotoButton;
@synthesize flashButton = _flashButton;
@synthesize positionButton = _positionButton;
@synthesize saveButton = _saveButton;
@synthesize cancelButton = _cancelButton;
@synthesize watermarkScroll = _watermarkScroll;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initView];
    
    if (iPhone5) {
        CGRect cRect = self.cameraView.frame;
        cRect.size.height = 455.f;
        if (ios7OrLater) {
            cRect.origin.y = 64.f;
        }
        self.cameraView.frame = cRect;
    }
    
    _preview = [AVCaptureVideoPreviewLayer layerWithSession: _session];
    _preview.frame = CGRectMake(0, 0, self.cameraView.frame.size.width, self.cameraView.frame.size.height);
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    [self.cameraView.layer addSublayer:_preview];
    [_session startRunning];
    
    [self.cameraView bringSubviewToFront:viewWaterMark];
    
    labelDate.text = [NSString stringWithFormat:@"名媛荟 - %@",getStringFromDate(@"yyyy-MM-dd HH:mm", [NSDate date])];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [_session stopRunning];
    [_session removeOutput:_captureOutput];
}

#pragma mark - Private
- (void) initView
{
    //1.创建会话层
    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPreset1280x720];
    
    //2.创建、配置输入设备
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [_device lockForConfiguration:nil];
    if([_device flashMode] == AVCaptureFlashModeOff){
        [_flashButton setImage:[UIImage imageNamed:@"watercam_flash_off.png"] forState:UIControlStateNormal];
    }
    else if([_device flashMode] == AVCaptureFlashModeAuto){
        [_flashButton setImage:[UIImage imageNamed:@"watercam_flash_auto.png"] forState:UIControlStateNormal];
    }
    else{
        [_flashButton setImage:[UIImage imageNamed:@"watercam_flash_on.png"] forState:UIControlStateNormal];
    }
    [_device unlockForConfiguration];
    
	NSError *error;
	_captureInput = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];
	if (!_captureInput)
	{
		NSLog(@"Error: %@", error);
		return;
	}
    [_session addInput:_captureInput];
    
    
    //3.创建、配置输出
    _captureOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
    [_captureOutput setOutputSettings:outputSettings];
	[_session addOutput:_captureOutput];
}


- (UIImage *)composeImage:(UIImage *)subImage toImage:(UIImage *)superImage atFrame:(CGRect)frame
{
    CGSize superSize = superImage.size;
    CGFloat widthScale = frame.size.width / self.cameraView.frame.size.width;
    CGFloat heightScale = frame.size.height / self.cameraView.frame.size.height;
    CGFloat xScale = frame.origin.x / self.cameraView.frame.size.width;
    CGFloat yScale = frame.origin.y / self.cameraView.frame.size.height;
    CGRect subFrame = CGRectMake(xScale * superSize.width, yScale * superSize.height, widthScale * superSize.width, heightScale * superSize.height);
    
    UIGraphicsBeginImageContext(superSize);
    [superImage drawInRect:CGRectMake(0, 0, superSize.width, superSize.height)];
    [subImage drawInRect:subFrame];
    __autoreleasing UIImage *finish = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return finish;
}

-(void) image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    // Was there an error?
    if (error != NULL)
    {
        // Show error message…
        NSLog(@"save error");
        [SVProgressHUD showErrorWithStatus:@"保存失败!"];
    }
    else  // No errors
    {
        // Show message image successfully saved
        NSLog(@"save success");
        //发送通知，使用新图片
        [[NSNotificationCenter defaultCenter] postNotificationName:@"selectNewsPicture" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)addHollowOpenToView:(UIView *)view
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.3f;
    animation.delegate = self;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeForwards;
    animation.type = @"cameraIrisHollowOpen";
    [view.layer addAnimation:animation forKey:@"animation"];
}

- (void)addHollowCloseToView:(UIView *)view
{
    CATransition *animation = [CATransition animation];//初始化动画
    animation.duration = 0.3f;//间隔的时间
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"cameraIrisHollowClose";
    
    [view.layer addAnimation:animation forKey:@"HollowClose"];
}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices)
    {
        if (device.position == position)
        {
            return device;
        }
    }
    return nil;
}

#pragma mark - Methors For Button Actions
- (void)takePhoto {
    [self addHollowCloseToView:self.cameraView];
    
    //get connection
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in _captureOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }
    
    //get UIImage
    [_captureOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:
     ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
         _saveButton.hidden = NO;
         _cancelButton.hidden = NO;
         [self addHollowCloseToView:self.cameraView];
         [_session stopRunning];
         [self addHollowOpenToView:self.cameraView];
         CFDictionaryRef exifAttachments = CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
         if (exifAttachments) {
             // Do something with the attachments.
         }
         // Continue as appropriate.
         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         _finishImage = [[UIImage alloc] initWithData:imageData] ;
     }];
}

- (void)changeFlash {
    if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] && [_device hasFlash])
    {
        [_flashButton setEnabled:NO];
        [_device lockForConfiguration:nil];
        if([_device flashMode] == AVCaptureFlashModeOff)
        {
            [_device setFlashMode:AVCaptureFlashModeAuto];
            [_flashButton setImage:[UIImage imageNamed:@"watercam_flash_auto.png"] forState:UIControlStateNormal];
        }
        else if([_device flashMode] == AVCaptureFlashModeAuto)
        {
            [_device setFlashMode:AVCaptureFlashModeOn];
            [_flashButton setImage:[UIImage imageNamed:@"watercam_flash_on.png"] forState:UIControlStateNormal];
        }
        else{
            [_device setFlashMode:AVCaptureFlashModeOff];
            [_flashButton setImage:[UIImage imageNamed:@"watercam_flash_off.png"] forState:UIControlStateNormal];
        }
        [_device unlockForConfiguration];
        [_flashButton setEnabled:YES];
    }

}

- (void)chagePosition {
    //添加动画
    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = .1f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"oglFlip";
    if (_device.position == AVCaptureDevicePositionFront) {
        animation.subtype = kCATransitionFromRight;
    }
    else if(_device.position == AVCaptureDevicePositionBack){
        animation.subtype = kCATransitionFromLeft;
    }
    [_preview addAnimation:animation forKey:@"animation"];
    
    NSArray *inputs = _session.inputs;
    for ( AVCaptureDeviceInput *input in inputs )
    {
        AVCaptureDevice *device = input.device;
        if ([device hasMediaType:AVMediaTypeVideo])
        {
            AVCaptureDevicePosition position = device.position;
            AVCaptureDevice *newCamera = nil;
            AVCaptureDeviceInput *newInput = nil;
            
            if (position == AVCaptureDevicePositionFront)
            {
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            }
            else
            {
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            }
            _device = newCamera;
            newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
            
            // beginConfiguration ensures that pending changes are not applied immediately
            [_session beginConfiguration];
            
            [_session removeInput:input];
            [_session addInput:newInput];
            
            // Changes take effect once the outermost commitConfiguration is invoked.
            [_session commitConfiguration];
            break;
        }
    }
}

- (void)useThisPhoto {
    UIGraphicsBeginImageContext(viewWaterMark.frame.size);
    [[viewWaterMark layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *waterImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGRect wmRect = CGRectMake(10, 240, 200, 100);//(10, 220, 240, 130)
    if (iPhone5) {
        wmRect = CGRectMake(10, 320, 200, 100);
    }
    _finishImage = [self composeImage:waterImage toImage:_finishImage atFrame:wmRect];
    
    UIImageWriteToSavedPhotosAlbum(_finishImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//    _saveButton.hidden = YES;
//    _cancelButton.hidden = YES;
//    [_session startRunning];
}

#pragma mark - Public
- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    NSLog(@"%d",btn.tag);
    if (btn.tag == 101) {
        //闪光灯
        [self changeFlash];
    }
    else if (btn.tag == 102) {
        //切换摄像头
//        [self changeFlash];
    }
    else if (btn.tag == 103) {
        //取消
        _saveButton.hidden = YES;
        _cancelButton.hidden = YES;
        [_session startRunning];
    }
    else if (btn.tag == 104) {
        //拍照
        [self takePhoto];
    }
    else if (btn.tag == 105) {
        //使用
        [self useThisPhoto];
    }
    else if (btn.tag == 106) {
        //收回输入文字框
        [tvEditting resignFirstResponder];
    }
    else if (btn.tag == 107) {
        //确定文字
        UIFont *cFont = tvContent.font;
        tvContent.text = tvEditting.text;
        tvContent.font = cFont;
        [tvEditting resignFirstResponder];
    }
    else if (btn.tag == 108) {
        //弹出输入文字框
        tvEditting.text = tvContent.text;
        [tvEditting becomeFirstResponder];
    }
    else if (btn.tag == 109) {
        //退出
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


#pragma mark - Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
//    NSLog(@"%@",NSStringFromCGRect(keyboardRect));
//    if (keyboardRect.origin.y + keyboardRect.size.height >= self.view.frame.size.height) {
//        return;
//    }
    viewMask.hidden = NO;
    viewEditting.hidden = NO;
    viewEditting.frame = CGRectMake(0,keyboardRect.origin.y - 60.f - 64.f, 320.f, 255.f);
}

- (void)keyboardWillHide:(NSNotification *)notification {
    viewMask.hidden = YES;
    viewEditting.hidden = YES;
//    viewEditting.frame = CGRectMake(0.f,50.f, 320.f, 255.f);
}


@end
